package com.dkd.service.impl;

import com.alibaba.fastjson.JSON;
import com.dkd.exception.LogicException;
import com.dkd.service.ESOrderService;
import com.dkd.vo.OrderVO;
import com.dkd.vo.Pager;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
@Slf4j
public class ESOrderServiceImpl implements ESOrderService {
	
	@Autowired
	private RestHighLevelClient esClient;
	
	@Override
	public Pager<OrderVO> search(Integer pageIndex, Integer pageSize, String orderNo, String openId, String startDate, String endDate) {
		//1. 创建请求对象
		SearchRequest searchRequest = new SearchRequest("order");
		
		BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
		//根据订单号查询
		if (!Strings.isNullOrEmpty(orderNo)) {
			boolQueryBuilder.must(QueryBuilders.termQuery("order_no", orderNo));
		}
		//根据openId查询
		if (!Strings.isNullOrEmpty(openId)) {
			boolQueryBuilder.must(QueryBuilders.termQuery("open_id", openId));
		}
		//根据时间范围查询
		if (!Strings.isNullOrEmpty(startDate) && !Strings.isNullOrEmpty(endDate)) {
			boolQueryBuilder.must(QueryBuilders.rangeQuery("update_time").gte(startDate).lte(endDate));
		}
		
		searchRequest.source().query(boolQueryBuilder);
		//按照最后更新时间由近到远的排序规则排序
		searchRequest.source().from((pageIndex - 1) * pageSize);
		searchRequest.source().size(pageSize);
		
		searchRequest.source().sort("update_time", SortOrder.DESC);
		//如果条数大于10000，显示实际条数
		searchRequest.source().trackTotalHits(true);
		
		//开始请求并处理响应
		try {
			SearchResponse response = esClient.search(searchRequest, RequestOptions.DEFAULT);
			List<OrderVO> orderVOList = Lists.newArrayList();
			//获取所有命中的订单并转换为订单VO对象
			SearchHits hits = response.getHits();
			for (SearchHit hit : hits) {
				String orderStr = hit.getSourceAsString();
				OrderVO orderVO = JSON.parseObject(orderStr, OrderVO.class);
				orderVOList.add(orderVO);
			}
			
			//新建分页对象并返回
			Pager<OrderVO> pager = new Pager<>();
			pager.setPageIndex(pageIndex);
			pager.setPageSize(pageSize);
			pager.setTotalCount(hits.getTotalHits().value);
			pager.setCurrentPageRecords(orderVOList);
			return pager;
		} catch (IOException e) {
			e.printStackTrace();
			log.error("搜索出错");
			throw new LogicException("搜索出错");
		}
	}
}